package com.qfedu.interceptor;

import com.qfedu.entity.User;
import com.qfedu.utils.StrUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * projectName: carCourier
 * author: CGY
 * time: 2020/9/17 15:02
 * description:
 */
//登陆的拦截器 必须要实现HandlerInterceptor接口
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        User user = (User) request.getSession().getAttribute(StrUtils.LOGIN_USER);
        if (user == null){
            //证明没有登陆需要跳转到登陆页面
            //1.在jquery中使用了ajax会又特殊的请求头 带有  .do
            String header = request.getHeader("X-Requested-With");
            if (header != null && header.equals("XMLHttpRequest")){
                response.getWriter().write("{\"code\":0,\"info\":\"未登录\"}");
            }else {
                response.sendRedirect(request.getContextPath()+"/login.html");
            }
            return false;
            //2.非ajax请求的 index.html transform.html
        }else {

            return true;
        }
    }
}
